import express from 'express'

import { clean } from '../utils/index.js'
import modules from '../db/schema/index.js'
const { Todo } = modules

const app = express()

const success = (data, message = '操作成功') => ({ code: 0, message, total: data?.length ? data.length : undefined, data })

app.get('/list', async ({ query, ...req }, res) => {
  const { page, size, ...restQuery } = query
  const queryList = Object.keys(clean(restQuery)).map(field => ({ [field]: isNaN(Number(query[field])) ? new RegExp(query[field], 'i') : query[field] }))
  const result = await Todo.find(queryList.length ? { $and: queryList } : undefined)
  res.send(success(result))
})

app.get('/view', async ({ query, ...req }, res) => {
  const { id } = query
  const result = await Todo.findById(id)
  res.send(success(result))
})

app.post('/add', async ({ body, ...req }, res) => {
  // const indexes = await Todo.collection.getIndexes()
  // console.log('[[indexes]] :', indexes)
  // await Todo.collection.dropIndex('_id_') // 删除冗余索引

  const doc = new Todo(body)
  const result = await doc.save()
  res.send(success(result, '添加成功'))
})

app.post('/edit', async ({ body, ...req }, res) => {
  const { id, ...rest } = body
  await Todo.updateOne({ _id: id }, rest)
  res.send(success(null, '更新成功'))
})

app.post('/delete', async ({ body, ...req }, res) => {
  const { id, ids } = body
  if (id) {
    await Todo.deleteOne({ _id: id })
  }
  if (ids) {
    await Todo.deleteMany({ _id: { $in: ids } })
  }
  res.send(success(null, '删除成功'))
})

export default app
